import React, { useEffect, useState, useRef } from 'react';
import { Modal, Form, Space, Divider } from 'antd';
import FormCondition from '@/components/FormCondition';
import PopImgShow from '@/components/PopImgShow';
import { connect, history } from 'umi';
import { Button, Row, Col } from 'antd';
import './index.less'
import { backgroundObj } from '@/utils/utils';
const MutualAllComponents = (props) => {
    const { data = {}, setFocusFlag, setDafaultData, fakeUnLikeHelpQa, fakeLikeHelpQaAnswer } = props
    const [visible, setVisible] = useState(false)
    const { content = '', replyUserHelpQaAnswerCommentList = [], likeFlag, unlikeFlag, unLikeAmount, viewAmount, operationFlag, likeAmount, answerAmount, createTime, username, collectAmount, userProfile } = data
    const { images = '', text } = content.length > 0 ? JSON.parse(content) : {}
    return <div className='MutualAll_change_box'>
        <div style={backgroundObj(userProfile)} className='MutualAll_profile_box'></div>
        <div className='MutualAll_content_box'>
            <div className='MutualAll_content_user'>
                <div className='MutualAll_content_username font_hide'>
                    {username}
                </div>
                <div className='MutualAll_content_loop'>
                    <div className={likeFlag === '1' ? 'MutualAll_content_loopIcon1' : 'MutualAll_content_loopIcon2'}>

                    </div>
                    <div className='MutualAll_content_font1'>
                        {likeAmount}
                    </div>
                </div>
                <div className='MutualAll_content_unLoop'>
                    <div className={unlikeFlag === '1' ? 'MutualAll_content_unLoopIcon1' : 'MutualAll_content_unLoopIcon2'}>

                    </div>
                    <div className='MutualAll_content_font1'>
                        {unLikeAmount}
                    </div>
                </div>
            </div>
            <div className='MutualAll_content_desc'>
                {text}
            </div>
            <div className='MutualAll_content_common'>
                <div className='MutualAll_common_address'>
                    {createTime}
                </div>
            </div>
            {replyUserHelpQaAnswerCommentList.map((item, index) => {
                if (replyUserHelpQaAnswerCommentList.length > 1 && !visible) {
                    if (index === 0) {
                        return <MutualAllComponentsInfo {...props} data={item}></MutualAllComponentsInfo>
                    }
                    else if (index === 1) {
                        return <div className='MutualAll_content_more'>
                            <div className='MutualAll_content_moreLiner'>

                            </div>
                            <div onClick={() => { setVisible(true) }} className='MutualAll_content_moreFont'>
                                展开{replyUserHelpQaAnswerCommentList.length - 1}条回复
                            </div>
                            <div className='MutualAll_content_moreIcon'>

                            </div>
                        </div>
                    }
                    return null
                }
                else {
                    return <MutualAllComponentsInfo {...props} data={item}></MutualAllComponentsInfo>
                }
            })}

        </div>
    </div>
}
const MutualAllComponentsInfo = (props) => {
    const { data = {}, setFocusFlag, setDafaultData } = props
    const { content = '', organizationUserId, id, commentId, replyUserName, replyUserHelpQaAnswerCommentList = [], likeFlag, unlikeFlag, unLikeAmount, viewAmount, operationFlag, likeAmount, answerAmount, createTime, username, collectAmount, userProfile } = data
    const { images = '', text } = content.length > 0 ? JSON.parse(content) : {}
    return <div className='MutualAll_change_box'>
        <div className='MutualAll_profile_box' style={backgroundObj(userProfile)}></div>
        <div className='MutualAll_content_box'>
            <div className='MutualAll_content_user'>
                <div className='MutualAll_content_username font_hide'>
                    {username}
                </div>
                <div className='MutualAll_content_loop'>
                    <div className={likeFlag === '1' ? 'MutualAll_content_loopIcon1' : 'MutualAll_content_loopIcon2'}>

                    </div>
                    <div className='MutualAll_content_font1'>
                        {likeAmount}
                    </div>
                </div>
                <div className='MutualAll_content_unLoop'>
                    <div className={unlikeFlag === '1' ? 'MutualAll_content_unLoopIcon1' : 'MutualAll_content_unLoopIcon2'}>

                    </div>
                    <div className='MutualAll_content_font1'>
                        {unLikeAmount}
                    </div>
                </div>
            </div>
            <div className='MutualAll_content_desc'>
                {replyUserName ? '回复' : ''}  {replyUserName ? <span className='MutualAll_content_span'>{replyUserName}:</span> : ''}  {text}
            </div>
            <div className='MutualAll_content_common'>
                <div className='MutualAll_common_address'>
                    {createTime}
                </div>
            </div>
        </div>
    </div>
}
const MessageAnswerModal = (props) => {
    const { visible = false, onClose, loading, dispatch, handleCallback, } = props;
    const { show = false, detail = {} } = visible;
    const { id, userHelpQaId } = detail
    const [list, setList] = useState([])
    const [data, setData] = useState({})
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState({
        page: 1,
        limit: 20
    })
    const [loadingMore, setLoadingMore] = useState(false); // 新增加载更多状态
    const containerRef = useRef(null); // 滚动容器引用
    const { content = '', viewAmount, createTime, username, collectAmount, userProfile } = data
    const { images = '', text } = content.length > 0 ? JSON.parse(content) : {}
    const imageList = images.split(',').filter(val => {
        return val
    })
    const fetchList = () => {
        setLoadingMore(true);
        dispatch({
            type: 'answering/fetchUserHelpQaAnswerCommentForAdmin',
            payload: {
                ...page,
                userHelpQaId: userHelpQaId,
                userHelpQaAnswerId: id
            },
            callback: (e, count) => {
                setList(prevList => [...prevList, ...e]); // 使用函数式更新确保数据正确合并
                setTotal(count);
                setLoadingMore(false);
            }
        })
    }
    const fetchData = () => {
        setLoadingMore(true);
        dispatch({
            type: 'answering/fetchUserHelpQaAnswerByIdForAdmin',
            payload: {
                id: id
            },
            callback: (e) => {
                setData(e)
            }
        })
    }
    // 处理滚动事件
    const handleScroll = () => {
        const container = containerRef.current;
        if (!container) return;

        // 滚动到底部判断（距离底部50px视为触底）
        const isAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;

        if (isAtBottom && !loadingMore && list.length < total) {
            // 更新页码并获取数据
            setPage(prevPage => ({
                ...prevPage,
                page: prevPage.page + 1
            }));
        }
    };

    useEffect(() => {
        if (show) {
            fetchList()
            fetchData()
        }
        else {
            setPage({
                page: 1,
                limit: 20
            })
            setList([])
        }
    }, [show])

    // 监听页码变化
    useEffect(() => {
        if (page.page > 1 && show) {
            fetchList();
        }
    }, [page.page]); // 当页码变化时加载数据

    // 添加滚动监听
    useEffect(() => {
        const container = containerRef.current;
        if (show && container) {
            container.addEventListener('scroll', handleScroll);
        }
        return () => {
            if (container) {
                container.removeEventListener('scroll', handleScroll);
            }
        };
    }, [show, loadingMore, list, total]);

    const modalProps = {
        title: '评论详情',
        width: 800,
        visible: show,
        maskClosable: true,
        destroyOnClose: true,
        zIndex: 1001,
        confirmLoading: loading,
        footer: null, // 隐藏默认底部按钮
    };

    return (
        <Modal {...modalProps} onCancel={onClose} >
            <div
                ref={containerRef}
                style={{ maxHeight: '640px', overflowY: 'auto', }}
                className='MutualAll_box'
            >
                <div className='MutualAll_card_box'>
                    <div className='MutualAll_card_userBox'>
                        <div className='MutualAll_card_userLeft'>
                            <div style={backgroundObj(userProfile)} className='MutualAll_card_profile'></div>
                            <div className='MutualAll_card_username font_hide'>
                                {username}
                            </div>
                        </div>
                    </div>
                    <div className='MutualAll_card_desc'>
                        {text}
                    </div>
                    <div className="Collect_list_showImage">
                        {imageList.map(val => {
                            return <div className="Collect_list_image">
                                <PopImgShow url={val}></PopImgShow>
                            </div>
                        })}
                    </div>
                    <div className='MutualAll_card_bottom'>
                        <div className='MutualAll_card_bottomLeft'>
                            回答于 {createTime}
                        </div>
                        <div className='MutualAll_card_bottomRight'>
                            <div className='MutualAll_card_iconBox'>
                                <div className={data.likeFlag === '1' ? 'MutualAll_card_icon MutualAll_card_iconStyle2' : 'MutualAll_card_icon MutualAll_card_iconStyle1'}></div>
                                <div className=''>
                                    {data.likeAmount}
                                </div>
                            </div>
                            <div className='MutualAll_card_iconBox'>
                                <div className='MutualAll_card_icon MutualAll_card_iconStyle3'></div>
                                <div className=''>
                                    {viewAmount}
                                </div>
                            </div>
                            <div className='MutualAll_card_iconBox'>
                                <div className={data.collectFlag === '1' ? 'MutualAll_card_icon MutualAll_card_iconStyle5' : 'MutualAll_card_icon MutualAll_card_iconStyle4'}></div>
                                <div className=''>
                                    {collectAmount}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <Divider></Divider>
                <div className='MutualAll_Components_box'>
                    <div className='MutualAll_Components_hf'>
                        共{total}条回复
                    </div>
                    {list.map(val => {
                        return <MutualAllComponents data={val}></MutualAllComponents>
                    })}
                </div>
            </div>
        </Modal >
    );
};

export default connect(({ order, loading }) => ({
    loading: loading.effects['answering/fetchListUserHelpQaAnswerForAdmin'],
}))(MessageAnswerModal);